import { getStatus } from "../utils/account";
import { message } from 'antd';

const base_url = "http://localhost:3500/api/";
const getbusinfo = (start, length) => { return base_url + "getbusinfo?start=" + start + "&length=" + length; };
const addbus = base_url + "addbus";
const deletebus = base_url + "deletebus";
const modifybusinfo = base_url + "modifybusinfo";
const getstationinfo = (start, length) => { return base_url + "getstationinfo?start=" + start + "&length=" + length; };
const addstation = base_url + "addstation";
const deletestation = base_url + "deletestation";
const modifystationinfo = base_url + "modifystationinfo";
const getadmininfo = (start, length) => { return base_url + "getadmininfo?start=" + start + "&length=" + length; };
const login = base_url + "login";
const register = base_url +"register";
const modifypassword = base_url + "modifypassword";
const deleteadmin = base_url + "deleteadmin";
const allline = base_url + "allline";
const getlineinfo = (start, length) => { return base_url + "getlineinfo?start=" + start + "&length=" + length; };
const modifybusinline = base_url + "modifybusinline";
const deletebusinline = base_url + "deletebusinline";
const addline = base_url + "addline";
const addstationinline = base_url + "addstationinline";
const deleteline = base_url + "deleteline";
const deletestationinline = base_url + "deletestationinline";
const getlinedata = base_url + "getlinedata";
const modifylineinfo = base_url + "modifylineinfo";

const busicon = "http://localhost:3500/static/busicon";
const stationicon = "http://localhost:3500/static/stationicon";

const giveRequest = (url, method, data=null, callback) => {
  if ( url !== login && url !== register && getStatus() === false ) {
    message.warn("请登录!");
    setTimeout(() => {
      window.location.href="/#/login";
    }, 2000);
    return;
  }

  var msg = {};

  switch (method) {
    case "GET":
      msg = {
        method: method,
      };
      break;
    case "POST":
      msg = {
        method: method,
        body: JSON.stringify(data),
        headers: new Headers({
          'Content-Type': 'application/json'
        }),
      };
      break;
    default:
      console.error("Method Error!!!");
      return;
  }

  fetch(url, msg)
  .then(res => res.json())
  .then(res => {
    callback(res);
  })
  .catch(err => {
    console.error(err);
    callback({
      status: "fail",
      data: null,
    });
  });
};

export {
  base_url,
  getbusinfo,
  deletebus,
  addbus,
  modifybusinfo,
  getstationinfo,
  addstation,
  deletestation,
  modifystationinfo,
  getadmininfo,
  login,
  register,
  modifypassword,
  deleteadmin,
  allline,
  getlineinfo,
  modifybusinline,
  deletebusinline,
  addline,
  addstationinline,
  deleteline,
  deletestationinline,
  giveRequest,
  getlinedata,
  busicon,
  stationicon,
  modifylineinfo,
};